﻿using System;
using System.Threading;
using System.Threading.Tasks;
using AyuBookmark.Common.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AyuBookmark.Service.Workers
{
    /// <summary>
    /// 定期清理工作服务
    /// </summary>
    public class CleanupWorker : BackgroundService
    {
        private readonly IBookmarkRepository _bookmarkRepository;
        private readonly IImageRepository _imageRepository;
        private readonly ILogger<CleanupWorker> _logger;
        private readonly TimeSpan _cleanupInterval;

        /// <summary>
        /// 初始化清理工作服务
        /// </summary>
        public CleanupWorker(
            IBookmarkRepository bookmarkRepository,
            IImageRepository imageRepository,
            ILogger<CleanupWorker> logger,
            TimeSpan? cleanupInterval = null)
        {
            _bookmarkRepository = bookmarkRepository ?? throw new ArgumentNullException(nameof(bookmarkRepository));
            _imageRepository = imageRepository ?? throw new ArgumentNullException(nameof(imageRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _cleanupInterval = cleanupInterval ?? TimeSpan.FromHours(6);
        }

        /// <summary>
        /// 执行后台清理任务
        /// </summary>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Cleanup Worker started with interval: {Interval}", _cleanupInterval);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await PerformCleanupTasksAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occurred during cleanup");
                }

                await Task.Delay(_cleanupInterval, stoppingToken);
            }

            _logger.LogInformation("Cleanup Worker stopped");
        }

        /// <summary>
        /// 执行所有清理任务
        /// </summary>
        private async Task PerformCleanupTasksAsync()
        {
            _logger.LogInformation("Starting cleanup tasks at: {Time}", DateTime.Now);

            // 1. 清理无效书签
            await CleanupInvalidBookmarksAsync();

            // 2. 清理未使用的图片
            await CleanupUnusedImagesAsync();

            // 3. 清理过期缓存
            await CleanupExpiredCacheAsync();

            _logger.LogInformation("Cleanup tasks completed at: {Time}", DateTime.Now);
        }

        /// <summary>
        /// 清理无效书签（404或无法访问）
        /// </summary>
        private async Task CleanupInvalidBookmarksAsync()
        {
            try
            {
                _logger.LogInformation("Starting invalid bookmarks cleanup");

                // 获取所有需要检查的书签
                var bookmarksToCheck = await _bookmarkRepository.GetBookmarksNeedingValidationAsync();

                foreach (var bookmark in bookmarksToCheck)
                {
                    if (!await IsUrlAccessibleAsync(bookmark.Url))
                    {
                        await _bookmarkRepository.MarkAsInvalidAsync(bookmark.Id);
                        _logger.LogWarning("Bookmark marked as invalid - ID: {Id}, URL: {Url}",
                            bookmark.Id, bookmark.Url);
                    }
                }

                _logger.LogInformation("Invalid bookmarks cleanup completed. Checked {Count} bookmarks",
                    bookmarksToCheck.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to cleanup invalid bookmarks");
                throw;
            }
        }

        /// <summary>
        /// 清理未使用的图片资源
        /// </summary>
        private async Task CleanupUnusedImagesAsync()
        {
            try
            {
                _logger.LogInformation("Starting unused images cleanup");

                var deletedCount = await _imageRepository.CleanupOrphanedImagesAsync();

                _logger.LogInformation("Unused images cleanup completed. Deleted {Count} images",
                    deletedCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to cleanup unused images");
                throw;
            }
        }

        /// <summary>
        /// 清理过期缓存
        /// </summary>
        private async Task CleanupExpiredCacheAsync()
        {
            try
            {
                _logger.LogInformation("Starting expired cache cleanup");

                // 实现缓存清理逻辑
                // 例如：await _cacheRepository.CleanupExpiredEntriesAsync();

                _logger.LogInformation("Expired cache cleanup completed");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to cleanup expired cache");
                throw;
            }
        }

        /// <summary>
        /// 检查URL是否可访问
        /// </summary>
        private async Task<bool> IsUrlAccessibleAsync(string url)
        {
            // 实现URL可达性检查
            // 示例：使用HttpClient发送HEAD请求
            return await Task.FromResult(true); // 简化实现
        }
    }
}